package com.zhentao.dataintegrity.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dataintegrity.domain.entity.IntegrityTask;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface IntegrityTaskMapper extends BaseMapper<IntegrityTask> {

    /**
     * 分页查询任务列表
     */
    @Select("<script>" +
            "SELECT * FROM di_integrity_task " +
            "WHERE is_delete = 0 " +
            "<if test='taskTitle != null and taskTitle != \"\"'> AND task_title LIKE CONCAT('%', #{taskTitle}, '%') </if>" +
            "<if test='taskStatus != null and taskStatus != \"\"'> AND task_status = #{taskStatus} </if>" +
            "<if test='triggerType != null and triggerType != \"\"'> AND trigger_type = #{triggerType} </if>" +
            "ORDER BY created_time DESC" +
            "</script>")
    IPage<IntegrityTask> selectTaskPage(Page<IntegrityTask> page,
                                      @Param("taskTitle") String taskTitle,
                                      @Param("taskStatus") String taskStatus,
                                      @Param("triggerType") String triggerType);

    /**
     * 查询需要执行的定时任务
     */
    @Select("SELECT * FROM di_integrity_task " +
            "WHERE task_status = 'ENABLED' " +
            "AND trigger_type = 'SCHEDULED' " +
            "AND next_run_time <= #{currentTime} " +
            "AND is_delete = 0")
    List<IntegrityTask> selectScheduledTasks(@Param("currentTime") LocalDateTime currentTime);

    /**
     * 更新任务运行状态
     */
    @Update("UPDATE di_integrity_task SET " +
            "last_run_time = #{lastRunTime}, " +
            "last_run_status = #{lastRunStatus}, " +
            "last_run_error = #{lastRunError}, " +
            "last_diff_rmb = #{lastDiffRmb}, " +
            "last_diff_usd = #{lastDiffUsd}, " +
            "next_run_time = #{nextRunTime} " +
            "WHERE id = #{id}")
    int updateRunStatus(@Param("id") Long id,
                       @Param("lastRunTime") LocalDateTime lastRunTime,
                       @Param("lastRunStatus") String lastRunStatus,
                       @Param("lastRunError") String lastRunError,
                       @Param("lastDiffRmb") BigDecimal lastDiffRmb,
                       @Param("lastDiffUsd") BigDecimal lastDiffUsd,
                       @Param("nextRunTime") LocalDateTime nextRunTime);

    /**
     * 更新任务状态
     */
    @Update("UPDATE di_integrity_task SET task_status = #{status} WHERE id = #{id}")
    int updateTaskStatus(@Param("id") Long id, @Param("status") String status);

    /**
     * 更新下次运行时间
     */
    @Update("UPDATE di_integrity_task SET next_run_time = #{nextRunTime} WHERE id = #{id}")
    int updateNextRunTime(@Param("id") Long id, @Param("nextRunTime") LocalDateTime nextRunTime);

    /**
     * 检查任务标题是否存在
     */
    @Select("SELECT COUNT(*) FROM di_integrity_task " +
            "WHERE task_title = #{taskTitle} " +
            "AND is_delete = 0 " +
            "AND (#{excludeId} IS NULL OR id != #{excludeId})")
    int checkTaskTitleExists(@Param("taskTitle") String taskTitle, @Param("excludeId") Long excludeId);

    /**
     * 查询任务统计信息
     */
    @Select("SELECT " +
            "COUNT(*) as total_tasks, " +
            "SUM(CASE WHEN task_status = 'ENABLED' THEN 1 ELSE 0 END) as enabled_tasks, " +
            "SUM(CASE WHEN last_run_status = 'SUCCESS' THEN 1 ELSE 0 END) as success_tasks, " +
            "SUM(CASE WHEN last_run_status = 'FAILED' THEN 1 ELSE 0 END) as failed_tasks " +
            "FROM di_integrity_task WHERE is_delete = 0")
    IntegrityTask getTaskStatistics();

    /**
     * 查询最近运行的任务
     */
    @Select("SELECT * FROM di_integrity_task " +
            "WHERE is_delete = 0 " +
            "AND last_run_time IS NOT NULL " +
            "ORDER BY last_run_time DESC " +
            "LIMIT #{limit}")
    List<IntegrityTask> selectRecentTasks(@Param("limit") int limit);
}
